# -*- coding: utf-8 -*-
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
from django.utils.encoding import smart_str, smart_unicode    #用可爱的Django自带的可爱的方法：smart_str、smart_unicode，就能完美处理中文了
import xml.etree.ElementTree as ET
import hashlib
import time
import cx_Oracle
import urllib
import re
from weixin_post import wx_post
import json
import datetime
from bs4 import BeautifulSoup
import mibossStaff


@csrf_exempt
def index(request):
    if request.method == 'GET':
        response = HttpResponse(checkSignature(request))
        return response
    elif request.method == 'POST':
        response = HttpResponse(responseMsg(request))
        print 'ok'
        return response
    else:
        return HttpResponse('Hello World')
        

def checkSignature(request):
    signature=request.GET.get('signature',None)
    timestamp=request.GET.get('timestamp',None)
    nonce=request.GET.get('nonce',None)
    echostr=request.GET.get('echostr',None)
    token='asdf1234'
    tmplist=[token,timestamp,nonce]
    tmplist.sort()
    tmpstr="%s%s%s"%tuple(tmplist)
    tmpstr=hashlib.sha1(tmpstr).hexdigest()
    if tmpstr==signature:
        return echostr
    else:
        return None
        
def responseMsg(request):

    rawStr = smart_str(request.body)
    root = ET.fromstring(rawStr)
    msg = {}
  
    for child in root:
        msg[child.tag] = smart_str(child.text)
        
    if msg['Content'] == '1':
        OracleData = GetOracle()
        replyContent = msg['Content'] + '. ' + OracleData
    elif msg['Content'] == '2':
        replyContent = msg['Content'] + '. ' + TianyaGet()
    elif msg['Content'] == '黄历':
        replyContent = huangli()
    elif msg['Content'] == '天气':
        replyContent = weather()
    elif msg['Content'] == '超时':
        wx_post('开始运行一周超时存储过程')
        OraRunPrc('YGL_WEEK_JOB')
        wx_post('一周超时存储过程运行完成')
        replyContent = '存储过程运行完成REPLY'    
    elif msg['Content'] == '退单':
        wx_post('开始运行一周退单存储过程')
        OraRunPrc('YGL_WEEK_RETURN')
        wx_post('一周退单存储过程运行完成')
        replyContent = '存储过程运行完成REPLY' 
    elif msg['Content'] == '邮件':
        replyContent = 'http://xxxxxx/oa/'
        returnNew = getReplyNew(msg, replyContent)
        print returnNew
        return returnNew
    elif 'miboss' in msg['Content']:
        print msg['Content']
        if msg['FromUserName'] == 'ozCpLuCmqOoKxtb8SICzDb1w69wg':
            sendUser = 'xxxxxx'
        else:
            sendUser = 'xxxxxx'
        input_string = msg['Content']
        input_string = input_string.replace('miboss', '')
        replyContent = mibossStaff.initEnable(input_string)
        print replyContent
        #wx_post(replyContent, sendUser)
        # return replyContent
    else:
        replyContent = '请重新输入...'
    return getReplyXml(msg,replyContent)

def GetOracle():
    print 'getoracle'
    con = cx_Oracle.connect("stat_yeguan/cdyg$151020@cd")
    cursor = con.cursor()
    query1 = cursor.execute("select created from all_objects where object_name='FZT_DD' and owner='STAT_YEGUAN'")
    rows = cursor.fetchall()
    rowCount1 = 'FZT_DD表的建立时间: '+ str(rows[0][0])
    
    query1 = cursor.execute("select sys_date from intf_exter_audit where rownum=1")
    rows = cursor.fetchall()
    rowCount2 = '稽核外挂表的处理时间: '+ str(rows[0][0])
       
    rowCount = rowCount1 + '   ' + rowCount2 
    cursor.close()
    con.close()
    print rowCount
    return rowCount

    
def OraRunPrc(v_prc):
    con = cx_Oracle.connect("stat_yeguan/cdyg$151020@cd")
    cursor = con.cursor()
    query1 = cursor.callproc(v_prc)
    cursor.close()
    con.close()
    return None

def weather():
    url = 'http://www.baidu.com/baidu?&ie=utf-8&word=%E5%A4%A9%E6%B0%94'
    content2 = urllib.urlopen(url).read()
    soup = BeautifulSoup(content2)
    c = soup.find('div', {"class":"op_weather4_twoicon_container_div"})
    e = []

    for link in c.find_all('a'):
        d = link.get_text()
        d = d.replace(u'\n','')
        d = ' '.join(d.split())
        e.append(d)
    text = '\n'.join(e)
    print text
    return text

    
def huangli():
    print 'huangli'
    try:
        url = 'http://m.laohuangli.net/'
        content2 = urllib.urlopen(url).read()
        soup = BeautifulSoup(content2, from_encoding="gb18030")
        c = soup.find_all('span', {'class': re.compile('title_txt1|title_txt2')})
        e = []
        for i in c:
            d = i.get_text()
            e.append(d)

        g = soup.find_all('div', id=re.compile('content_left'), limit=4)
        for j in g:
            k = j.get_text()
            e.append(k)
        texts = '\n'.join(e)
    except Exception as e:
        print e
        texts = 'time out'
       
    return texts
   
def TianyaGet():
    f = urllib.urlopen('http://www.tianya.cn/api/tw?method=userinfo.ice.getUserTotalReplyList&params.userId=78356465&params.pageSize=5&params.bMore=true&var=UserTotalReplyList&_=1410418443268')
    content = f.read()
    f.close()

    result = re.search('"title":"(.*?)","item_name"', content)
    if result:
        result_c = result.group(1).replace('"', '').replace('reply_time:', '') 
    else:
        result_c = '无数据'
    return result_c    

def getReplyXml(msg,replyContent):
    extTpl = """<xml>
             <ToUserName><![CDATA[%s]]></ToUserName>
             <FromUserName><![CDATA[%s]]></FromUserName>
             <CreateTime>%s</CreateTime>
             <MsgType><![CDATA[text]]></MsgType>
             <Content><![CDATA[%s]]></Content>
             <FuncFlag>0</FuncFlag>
             </xml>"""
    extTpl = extTpl % (msg['FromUserName'], msg['ToUserName'], str(int(time.time())), replyContent)
    print extTpl
    return extTpl

#返回网页消息    
def getReplyNew(msg, replyContent):
    extTpl = """<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[news]]></MsgType>
<ArticleCount>1</ArticleCount>
<Articles>
<item>
<Title><![CDATA[邮件列表]]></Title> 
<Description><![CDATA[点击查看最近新收到的邮件]]></Description>
<PicUrl><![CDATA[http://pic6.wed114.cn/20140208/20140208110625061.JPG]]></PicUrl>
<Url><![CDATA[%s]]></Url>
</item>
</Articles>
</xml>"""
    extTpl = extTpl % (msg['FromUserName'], msg['ToUserName'], str(int(time.time())), replyContent)
    return extTpl